#coding=utf-8
#!/usr/bin/python

'''
Created on 2012-11-17

@author: Neo.Chen
'''

'''
功能：
'''
import os
import threading
import socketserver

users = []

class MyTCPHandler(socketserver.StreamRequestHandler):
    def handle(self):
        username = None
        while True:
            self.data = self.rfile.readline().strip()
            cur_thread = threading.currentThread()
            print("RECV from ", self.client_address[0])
            cmd = self.data
            if cmd == None or len(cmd) == 0:
                break;
            print(cmd)
            # business logic here
            try:
                if cmd.startswith('echo'):
                    result = cmd[5:]
                elif cmd.startswith('login'):
                    username = cmd[6:]
                    users.append({username:self.wfile})
                    result = username + ' logined.'
                elif cmd == 'quit':
                    break
                else:
                    result = 'error cmd'
                self.wfile.write(result)
                self.wfile.write('\n')
            except:
                print('error')
                break
        try:
            if username != None:
                users.remove(username)
        except:
            pass
        print(username, ' closed.')

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def server1():
    HOST, PORT = "localhost", 9999

    server = ThreadedTCPServer((HOST, PORT), MyTCPHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.setDaemon(True)
    server_thread.start()
    server.serve_forever()


class MyHandler(socketserver.BaseRequestHandler):
    def handle(self):
        while True:
            dataReceived = self.request.recv(1024)
            if not dataReceived: break
            #self.request.send(dataReceived)
            #print dataReceived
            if dataReceived == 'cmd=1':
                os.system('/home/cgi/scp.exp')
                self.request.send(dataReceived+'&result=1\n')
            else:
                self.request.send(dataReceived+'&result=0\n')
def server2():
    myServer = socketserver.ThreadingTCPServer(('localhost',6100), MyHandler)
    myServer.serve_forever()

def main():
    server2()

if __name__ == '__main__':
    main()

